
import { defineStore } from 'pinia';
import { isEqual } from "lodash"

export const useListStore = defineStore('list', {
  state: () => ({
    // 历史播放数据
    historyList: JSON.parse(localStorage.getItem('historyList')) || [],
    // 正在播放列表
    playList: JSON.parse(localStorage.getItem('playList')) || [],
    // 正在播放的歌曲索引
    MusicIndex: -1,
    // 当前播放的音乐对象
    // music: computed(() => { return this.playList[this.MusicIndex] || {} }),
    // 音乐歌词
    lyric: [],
    // 播放状态(未播放的状态为true)
    playing: true,
    // 当前播放音乐url
    url: '',
    // audio
    audioDom: null,
    // 当前音乐播放时间
    currentTime: 0,
    // 当前音乐总时长
    // duration: 0,
    // 当前播放的歌词索引
    lyIndex: 0,
    // 音量大小
    voice: 50,
    // 播放模式
    modeKey: 0,
  }),
  getters: {
    // 计算当前播放音乐对象
    music: (state) => state.playList[state.MusicIndex] || {},
    duration: (state) => (
      Number(state.music.duration?.split(":")[0]) * 60 + Number(state.music.duration?.split(":")[1])) || 0
  },
  actions: {
    setMusicIndex(data) {
      this.MusicIndex = data
    },
    setModeKey() {
      this.modeKey = (this.modeKey + 1) % 4
    },
    setCurrentTime(data) {
      this.currentTime = data
    },
    setLyIndex(data) {
      this.lyIndex = data
    },
    // setDuration(data) {
    //   this.duration = data
    // },
    setAudioDom(data) {
      this.audioDom = data
    },
    setPlaying() {
      this.playing = !this.playing
    },
    setUrl(data) {
      this.url = data
    },
    setMusic(data) {
      // this.music = data
      this.MusicIndex = this.playList.findIndex(item => {
        return item.id === data.id;
      });
    },
    // 处理歌词
    parseLyric(lrc) {
      const timeExp = /\[(\d{2,}):(\d{2})(?:\.(\d{2,3}))?]/g
      const lines = lrc.split("\n")
      const lyric = []
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i]
        const result = timeExp.exec(line)
        if (!result) {
          continue
        }
        const text = line.replace(timeExp, "").trim()
        if (text) {
          lyric.push({
            time: (result[1] * 6e4 + result[2] * 1e3 + (result[3] || 0) * 1) / 1e3,
            text,
          })
        }
      }
      return lyric
    },
    setLyric(data) {
      this.lyric = this.parseLyric(data)
    },
    addHistory(detail) {
      if (!this.historyList?.some(item => isEqual(item, detail))) {
        this.historyList.unshift(detail)
        localStorage.setItem('historyList', JSON.stringify(this.historyList))
        if (!this.playList?.some(item => isEqual(item, detail))) {
          this.playList.unshift(detail)
          localStorage.setItem('playList', JSON.stringify(this.playList))
        }
      }
    },

    deleteHistory(id) {
      if (this.historyList.length) {
        this.historyList = this.historyList.filter((item) => {
          return item.id !== id
        })
      }
      localStorage.setItem('historyList', JSON.stringify(this.historyList))
    },

    clearHistory() {
      this.historyList = []
      localStorage.setItem('historyList', JSON.stringify(this.historyList))
    },

    setPlayList(data) {
      let tmp = JSON.parse(localStorage.getItem('historyList')) || []
      this.playList.unshift(...tmp, ...data)
      localStorage.setItem('playList', JSON.stringify(this.playList))
    },

    deletePlayList(id) {
      if (this.playList.length) {
        this.playList = this.playList.filter((item) => {
          return item.id !== id
        })
      }
      localStorage.setItem('playList', JSON.stringify(this.playList))
    },

    clearPlayList() {
      this.playList = []
      localStorage.setItem('playList', JSON.stringify(this.playList))
    },
  }

  // let historyList = ref([])

  // let playList = ref([])

  // let music = ref({})

  // function setMusic(data) {
  //   // debugger
  //   console.log('111111111111112222', data);
  //   music = data
  //   console.log('111111111111112222');

  // }
  // function addHistory(detail) {
  //   if (!historyList.some(item => isEqual(item, detail))) {
  //     historyList.unshift(detail)
  //     playList.unshift(detail)
  //     localStorage.setItem('historyList', JSON.stringify(historyList.value))
  //     localStorage.setItem('playList', JSON.stringify(playList.value))
  //   }
  // }

  // function deleteHistory(id) {
  //   if (historyList.length) {
  //     historyList.value = historyList.filter((item) => {
  //       return item.id !== id
  //     })
  //   }
  //   localStorage.setItem('historyList', JSON.stringify(historyList.value))
  // }

  // function clearHistory() {
  //   historyList.value = []
  //   localStorage.setItem('historyList', JSON.stringify(historyList.value))
  // }

  // function setPlayList(data) {
  //   let tmp = JSON.parse(localStorage.getItem('historyList')) || []
  //   playList.unshift(...tmp, ...data)
  //   localStorage.setItem('playList', JSON.stringify(playList.value))
  // }

  // function deletePlayList(id) {
  //   if (playList.length) {
  //     playList.value = playList.filter((item) => {
  //       return item.id !== id
  //     })
  //   }
  //   localStorage.setItem('playList', JSON.stringify(playList.value))
  // }

  // function clearPlayList() {
  //   playList.value = []
  //   localStorage.setItem('playList', JSON.stringify(playList.value))
  // }
  // return { historyList, addHistory, deleteHistory, clearHistory, playList, setPlayList, deletePlayList, clearPlayList, music, setMusic }
})

/*
export const useCounterStore = defineStore('counter', () => {
  // 使用ref来定义可变的状态
  const count = ref(0);

  // 使用computed来创建派生状态
  const doubleCount = computed(() => count.value * 2);

  // 直接定义方法，而不是放在actions对象中
  function increment() {
    count.value++;
  }

  function decrement() {
    count.value--;
  }

  // 注意：原始代码中的increment方法接收一个参数amount，这里为了保持一致也进行调整
  function incrementBy(amount) {
    count.value += amount;
  }

  // 将状态、计算属性和方法一起返回
 return { count, doubleCount, increment, decrement, incrementBy };
});
*/

